<template>
  <div class="app-container">
    <div v-if="nowBasePath.length>0">
      <span>当前位置:</span><strong>{{nowBasePath}}</strong>
    </div>
    <div v-if="nowBasePath.length==0">
      <span>当前位置:</span><strong>根路径</strong>
    </div>
    <div style="padding: 5px;"></div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-arrow-left"
          size="mini"
          @click="getBack"
          v-hasPermi="['system:config:add']"
        >返回上一级</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-if="backSteps.length>0"
          v-hasPermi="['system:config:edit']"
        >上传文件</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-folder-add"
          size="mini"
          v-if="backSteps.length>0"
          @click="newPackage"
          v-hasPermi="['system:config:remove']"
        >新建文件夹</el-button>
      </el-col>
      <right-toolbar @queryTable="refreshlist"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bdFileList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="文件类型" align="center" :formatter="dbfileFormat" prop="type" />
      <el-table-column label="文件或目录名" align="center" prop="simpleName" :show-overflow-tooltip="true" />
      <el-table-column label="大小" align="center" prop="readableSize" :show-overflow-tooltip="true" />
      <el-table-column label="描述" align="center" prop="info" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.type=='dir'"
            @click="into(scope.row)"
            v-hasPermi="['filemanage:bdfile:into']"
          >进入文件夹</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            v-if="backSteps.length>0"
            @click="zippackage(scope.row)"
            v-hasPermi="['system:config:remove']"
          >压缩为zip</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            v-if="scope.row.type=='file'"
            @click="fileDownLoad(scope.row)"
            v-hasPermi="['system:config:remove']"
          >下载</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            v-if="scope.row.simpleName.includes('.zip')"
            @click="unPackage(scope.row)"
            v-hasPermi="['system:config:remove']"
          >解压</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="delFile(scope.row)"
            v-hasPermi="['system:config:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="参数名称" prop="configName">
          <el-input v-model="form.configName" placeholder="请输入参数名称" />
        </el-form-item>
        <el-form-item label="参数键名" prop="configKey">
          <el-input v-model="form.configKey" placeholder="请输入参数键名" />
        </el-form-item>
        <el-form-item label="参数键值" prop="configValue">
          <el-input v-model="form.configValue" placeholder="请输入参数键值" />
        </el-form-item>
        <el-form-item label="系统内置" prop="configType">
          <el-radio-group v-model="form.configType">
            <el-radio
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 文件导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        :headers="upload.headers"
        :action="upload.url + '?path=' + nowBasePathrep"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBdfile,intoFile,newPackage, delFile,getConfig, zippackage,unPackage,fileDownLoad, addConfig, updateConfig, exportConfig, refreshCache } from "@/api/filemanage/bdfile";
import { getToken } from "@/utils/auth";

export default {
  name: "Config",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 目录表格数据
      bdFileList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 类型数据字典
      typeOptions: [],
      //文件类型数据字典
      bdFileOptions: [],
      // 日期范围
      dateRange: [],
      //当前路径
      nowBasePath: "",
      backSteps: [],
      toUpload: false,
      nowBasePathrep: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {},
      // 文件导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/filemanage/bdfile/importData"
      },
      // 表单校验
      rules: {
        configName: [
          { required: true, message: "参数名称不能为空", trigger: "blur" }
        ],
        configKey: [
          { required: true, message: "参数键名不能为空", trigger: "blur" }
        ],
        configValue: [
          { required: true, message: "参数键值不能为空", trigger: "blur" }
        ]
      }
    };
  },
  //在实例被创建之后调用
  created() {
    this.getList();
    this.getDicts("sys_yes_no").then(response => {
      this.typeOptions = response.data;
    });
    this.getDicts("bdfile_type").then(response => {
      this.bdFileOptions = response.data;
    });
  },
  methods: {
    /** 查询参数列表 */
    getList() {
      this.loading = true;
      listBdfile(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.bdFileList = response.rows;
          this.total = response.total;
          this.nowBasePath = response.nowBasePath;
          this.loading = false;
        }
      );
    },
    // 参数系统内置字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.configType);
    },
    // 字典状态字典翻译
    dbfileFormat(row) {
      return this.selectDictLabel(this.bdFileOptions, row.type);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        configId: undefined,
        configName: undefined,
        configKey: undefined,
        configValue: undefined,
        configType: "Y",
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.handleQuery();
    },
    /** 返回上一级 */
    getBack() {
      if (this.backSteps.length == 1) {
        //删除 arrayObject 的最后一个元素，把数组长度减 1，并且返回它删除的元素的值。如果数组已经为空，则 pop() 不改变数组，并返回 undefined 值
        this.backSteps.pop();
        listBdfile(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.bdFileList = response.rows;
          this.total = response.total;
          this.nowBasePath = response.nowBasePath;
          this.loading = false;
        });
      } else if (this.backSteps.length > 1) {
        this.backSteps.pop();
        var path = this.backSteps[this.backSteps.length - 1];
        console.log(path)
        intoFile({ path: path }).then(response => {
            this.bdFileList = response.rows;
            this.total = response.total;
            this.nowBasePath = response.nowBasePath;
            this.loading = false;
        });
      } else {
        listBdfile(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.bdFileList = response.rows;
          this.total = response.total;
          this.nowBasePath = response.nowBasePath;
          this.loading = false;
        });
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.configId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const configId = row.configId || this.ids
      getConfig(configId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改参数";
      });
    },
    /** 进入文件夹 */
    into(row) {
      console.log("====="+row.path)
      this.loading = true;
      this.backSteps.push(row.path);
      intoFile({ path: row.path }).then(response => {
          this.bdFileList = response.rows;
          this.total = response.total;
          this.nowBasePath = response.nowBasePath;
          this.loading = false;
        }
      );
    },

    /** 刷新列表 */
    refreshlist(row) {
      this.loading = true;
      intoFile({ path: this.nowBasePath }).then(response => {
          this.bdFileList = response.rows;
          this.total = response.total;
          this.nowBasePath = response.nowBasePath;
          this.loading = false;
      });
    },

    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.configId != undefined) {
            updateConfig(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addConfig(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 新建文件夹 */
    newPackage(row) {
      this.$prompt('请输入文件夹名称', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then(({ value }) => {
        newPackage({ path: this.nowBasePath,simpleName: value}).then(response => {
          this.$alert(response.status, "创建结果", { dangerouslyUseHTMLString: true });
          intoFile({ path: this.nowBasePath }).then(response => {
            this.bdFileList = response.rows;
            this.total = response.total;
            this.nowBasePath = response.nowBasePath;
            this.loading = false;
          });
        });
      }).catch(() => {});
    },

    /** 删除文件 */
    delFile(row) {
      this.$confirm('此操作将删除该文件，是否继续？','警告！！',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type:'warning'
      }).then(()=>{
        delFile({ path: this.nowBasePath+'\\'+row.simpleName}).then(response => {
          this.$alert(response.status, "删除结果", { dangerouslyUseHTMLString: true });
          intoFile({ path: this.nowBasePath }).then(response => {
            this.bdFileList = response.rows;
            this.total = response.total;
            this.nowBasePath = response.nowBasePath;
            this.loading = false;
          });
        });
      });
    },

    /** 压缩文件 */
    zippackage(row) {
      console.log("压缩打包下载：" + row.path);
      zippackage({ path: row.path }).then(response => {
        this.$alert(response.status, "压缩结果", { dangerouslyUseHTMLString: true });
        intoFile({ path: this.nowBasePath }).then(response => {
          this.bdFileList = response.rows;
          this.total = response.total;
          this.nowBasePath = response.nowBasePath;
          this.loading = false;
        });
      });
    },

    /** 解压文件 */
    unPackage(row) {
      console.log("解压文件路径：" + row.path);
      unPackage({ path: row.path }).then(response => {
        this.$alert(response.status, "解压结果", { dangerouslyUseHTMLString: true });
        intoFile({ path: this.nowBasePath }).then(response => {
          this.bdFileList = response.rows;
          this.total = response.total;
          this.nowBasePath = response.nowBasePath;
          this.loading = false;
        });
      });
    },

    /** 下载文件 */
    fileDownLoad(row) {
      fileDownLoad({ path: row.path,simpleName: row.simpleName}).then(response => {
        const a = document.createElement('a');
        a.setAttribute('download', row.simpleName);
        a.setAttribute('target', '_blank');
        a.setAttribute('href', response.msg);
        a.click();
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有参数数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportConfig(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    /** 刷新缓存按钮操作 */
    handleRefreshCache() {
      refreshCache().then(() => {
        this.msgSuccess("刷新成功");
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户上传";
      this.upload.open = true;
      let reg=new RegExp('\\\\','g');//g代表全部
      this.nowBasePathrep = this.nowBasePath.replace(reg,"@");
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      intoFile({ path: this.nowBasePath }).then(response => {
          this.bdFileList = response.rows;
          this.total = response.total;
          this.nowBasePath = response.nowBasePath;
          this.loading = false;
      });
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
